package com.ry.est.annotations;

import com.ry.est.entity.Users;
import com.ry.est.service.TokenService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

@Slf4j
public class TokenUserHandlerMethodArgumentResolver
        implements HandlerMethodArgumentResolver {
    private TokenService tokenService;
    public void setTokenService(TokenService tokenService) {
        this.tokenService = tokenService;
    }
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        //是否支持这个方法参数
        TokenUser ann = parameter.getParameterAnnotation(TokenUser.class);
        if (ann != null){
            return true;
        }
        return false;
    }
    @Override
    public Object resolveArgument(MethodParameter methodParameter,
                                  ModelAndViewContainer modelAndViewContainer,
                                  NativeWebRequest nativeWebRequest,
                                  WebDataBinderFactory webDataBinderFactory) throws Exception {
        //从request对象中获取token头
        String token = nativeWebRequest.getHeader("token");

        if (token == null){
            return null;
        }
        log.info(token);
        //然后使用tokenService获取用户信息，返回
        Users userInfoByToken = tokenService.getUserInfoByToken(token);
        return userInfoByToken;
    }
}
